﻿using Emgu.CV;
using Emgu.CV.Structure;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace MaiYao
{
    public class Ocr选项_
    {
        [JsonProperty("ocr.language")]
        public string language;
        [JsonProperty("ocr.cls")]
        public bool cls;
        [JsonProperty("ocr.limit_side_len")]
        public int limit_side_len;
        [JsonProperty("tbpu.parser")]
        public string parser;
        [JsonProperty("data.format")]
        public string format;
    }

    public class Ocr数据_
    {
        public string base64;
        public Ocr选项_ options;
    }

    public class Ocr结果
    {
        [JsonProperty("code")]
        public int 代码;
        [JsonProperty("data")]
        public string 内容;
        [JsonProperty("score")]
        public double 准确率;
        [JsonProperty("time")]
        public double 时间;
        [JsonProperty("timestamp")]
        public double 时间戳;
    }

    class Ocr
    {
        private static readonly string Url = "http://127.0.0.1:1224/api/ocr";
        private static readonly RestClient client = new RestClient(Url);
        private static readonly Ocr选项_ 选项 = new Ocr选项_
        {
            language = "models/config_chinese.txt",
            cls = false,
            limit_side_len = 960,
            parser = "single_none",
            format = "text"
        };

        private static string ImageToBase64(Mat mat, ImageFormat format = null)
        {
            using (Bitmap bitmap = mat.ToImage<Bgr, byte>().ToBitmap())
            {
                return ImageToBase64(bitmap, format);
            }
        }

        private static string ImageToBase64(Bitmap bmp, ImageFormat format = null)
        {
            if (format == null)
            {
                format = ImageFormat.Bmp;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Save(ms, format);
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        private static Ocr结果 识别请求(string base64)
        {
            var data = new Ocr数据_
            {
                base64 = base64,
                options = 选项
            };
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            var dataJson = JsonConvert.SerializeObject(data);
            request.AddJsonBody(dataJson);
            var content = client.Execute(request).Content;
            return JsonConvert.DeserializeObject<Ocr结果>(content);
        }

        public static Ocr结果 识别文本(Bitmap mat)
        {
            return 识别请求(ImageToBase64(mat));
        }

        public static Ocr结果 识别文本(Mat mat)
        {
            return 识别请求(ImageToBase64(mat));
        }
    }
}
